<template>
	<div>
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
			status-icon
			scroll-to-error
			:validate-on-rule-change="false"
		>
			<el-card shadow="never">
				<div class="card-title">基本信息</div>
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="请选择路线" prop="line_id">
							<el-select @change="changeLine()" style="width: 100%" v-model="ruleForm.line_id" placeholder="请选择路线">
								<el-option
									v-for="(item, index) in globalStore.lineLists"
									:key="index"
									:label="item.start_country + item.start_country_code + ' ✈ ' + item.end_country + item.end_country_code"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="渠道" prop="channel_id">
							<el-select style="width: 100%" v-model="ruleForm.channel_id" placeholder="选择路线后选择">
								<el-option
									style="margin-bottom: 15px; border-top: 1px solid #d6d6d6; border-bottom: 1px solid #d6d6d6"
									v-for="(item, index) in channelList"
									:key="index"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>
			<el-card shadow="never" style="margin-top: 10px">
				<div class="card-title">批量上传</div>
				<el-row :gutter="10">
					<el-col style="margin-bottom: 10px" :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<div
							v-upload-file="{
								type: ['xls', 'xlsx'],
								size: 5,
								limit: 1
							}"
							@upload="readExcelFile"
							class="load"
						>
							<div>
								<el-icon style="font-size: 60px; color: var(--el-color-primary)"><UploadFilled /></el-icon>
								<div style="font-size: 14px">上传文件</div>
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<div @click="downLoadModel()" class="load">
							<div>
								<el-icon style="font-size: 60px; color: var(--el-color-primary)"><Download /></el-icon>
								<div style="font-size: 14px">下载模版</div>
							</div>
						</div>
					</el-col>
				</el-row>
			</el-card>
			<el-card shadow="never" style="margin-top: 10px">
				<div class="card-title">订单预览</div>
				<el-row :gutter="10">
					<el-table
						empty-text="请上传文件"
						:data="TableList"
						style="width: 100%"
						border
						:header-cell-style="{ color: 'var(--el-color-primary)' }"
					>
						<el-table-column minWidth="120" prop="client_code" label="客户代码"> </el-table-column>
						<el-table-column width="120" prop="user_mark" label="客户唛头"> </el-table-column>
						<el-table-column width="150" prop="order_no" label="来源单号"> </el-table-column>
						<el-table-column width="120" prop="sender.name" label="寄件人"> </el-table-column>
						<el-table-column width="150" prop="mobile" label="寄件电话">
							<template #default="{ row }">
								<span>+{{ row.sender.area_code }} {{ row.sender.mobile }}</span>
							</template>
						</el-table-column>
						<el-table-column width="120" prop="client_address.name" label="收件人"> </el-table-column>
						<el-table-column width="150" prop="mobile" label="收件电话">
							<template #default="{ row }">
								<span>+{{ row.client_address.area_code }} {{ row.client_address.mobile }}</span>
							</template>
						</el-table-column>
						<el-table-column width="80" prop="weight_report" label="包裹重量"> </el-table-column>
						<!-- <el-table-column width="80" prop="total_num" label="商品数量"> </el-table-column>
						<el-table-column width="120" prop="total_price" label="申报价值(KRW)"> </el-table-column> -->
						<el-table-column width="120" prop="express_type" label="产品类型"> </el-table-column>

						<el-table-column fixed="right" label="操作" prop="addtime" width="160">
							<template #default="{ row, $index }">
								<el-button @click="cheack(row)" type="primary">查看</el-button>
								<el-button @click="delet($index)" type="primary">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-row>
			</el-card>
			<div class="buttons">
				<el-button @click="submitOrder()" type="primary">完 成</el-button>
			</div>
		</el-form>
		<el-drawer size="800px" v-model="drawer" title="查看商品">
			<el-table
				empty-text="请上传文件"
				:data="rowList"
				style="width: 100%"
				border
				:header-cell-style="{ color: 'var(--el-color-primary)' }"
			>
				<!-- <el-table-column prop="cate1" label="一级类名"> </el-table-column> -->
				<el-table-column prop="cate2" label="分类"> </el-table-column>
				<!-- <el-table-column prop="title" label="商品名称"> </el-table-column>
				<el-table-column prop="amount" label="售价(KRW)"> </el-table-column> -->
				<el-table-column prop="num" label="商品数量"> </el-table-column>
			</el-table>
		</el-drawer>
		<el-dialog v-model="dialogVisible" title="上传结果" width="500">
			<span>
				上传成功 <span style="color: var(--el-color-primary)">{{ result.successData.length }}</span> 条</span
			>,
			<span>
				上传失败 <span style="color: var(--el-color-primary)">{{ result.errorData.length }}</span> 条</span
			>
			<div style="margin-top: 10px">
				<div v-for="(item, index) in result.errorData" :key="index">
					<span style="margin-right: 20px">包裹号: {{ item.data.order_no }}</span>
					<span>{{ item.err_msg }}</span>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="resetForm(ruleFormRef)"> 确 定 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, computed } from "vue";
import { GlobalStore } from "@/stores";
import type { FormInstance, FormRules } from "element-plus";
import XLSX from "xlsx-js-style";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { sheet2Data } from "@/utils/excel";
import { AddressCorrectNew } from "@/api/base/index";
import { listChannel, createBatch } from "@/api/modules/makeorder";

import _ from "lodash";
const downLoadModel = () => {
	window.location.href =
		"https://syd-pub.oss-cn-qingdao.aliyuncs.com/download/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93/%E5%88%B6%E5%8D%95%E6%A8%A1%E6%9D%BF.xlsx";
};
const dialogVisible = ref(false);
const TableList: any = ref([]);
const globalStore = GlobalStore();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	line_id: "",
	channel_id: ""
});
const rules = reactive<FormRules>({
	line_id: [{ required: true, message: "请选择路线" }],
	channel_id: [{ required: true, message: "请选择渠道" }]
});
const channelList: any = ref([]);
const changeLine = () => {
	ruleForm.channel_id = "";
	//获取渠道列表
	listChannel({
		line_id: ruleForm.line_id,
		limit: 1000
	}).then((res: any) => {
		channelList.value = res.data.list;
	});
};
/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
	return new Promise(resolve => {
		let reader = new FileReader();
		reader.readAsArrayBuffer(file);
		reader.onload = ev => {
			resolve(ev.target?.result);
		};
	});
};

const addressCorrect = (address: any) => {
	return new Promise((resolve, reject) => {
		if (address) {
			AddressCorrectNew({
				country: "CN",
				address: address
			}).then((res: any) => {
				resolve({
					province: res.data.state,
					city: res.data.city,
					district: res.data.district,
					detailed: res.data.detail
				});
			});
		} else {
			resolve({
				province: "",
				city: "",
				district: "",
				detailed: ""
			});
		}
	});
};
/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
const readExcelFile = async (e: any) => {
	const loading = ElLoading.service({
		lock: true,
		text: "上传中,请稍后...",
		background: "rgba(0, 0, 0, 0.7)"
	});
	let data = await readFile(e);
	let workbook = XLSX.read(data);
	let worksheet = workbook.Sheets[workbook.SheetNames[0]];
	// data = XLSX.utils.sheet_to_json(worksheet);
	let file = sheet2Data(worksheet, "ABC");
	let arr = [
		"包裹号",
		"客户代码",
		"客户唛头",
		"寄件人",
		"国际区号",
		"电话",
		"国家",
		"详细地址",
		"包裹重量(KG)",
		"寄件人邮编",
		"收件人姓名",
		"收件地址（需要填写正确省市区）",
		"收件人手机号码",
		"收件人邮编",
		"备注",
		"快递产品类型",
		"卫衣",
		"开衫",
		"毛衣/针织衫",
		"衬衫",
		"T恤",
		"背心",
		"内衣",
		"连衣裙",
		"半身裙",
		"休闲裤",
		"短款",
		"牛仔裤",
		"羊绒大衣",
		"风衣",
		"西服",
		"羽绒服",
		"棉服",
		"夹克",
		"发夹",
		"发圈",
		"发箍",
		"项链",
		"手链/脚链",
		"耳环",
		"运动鞋",
		"皮鞋",
		"拖鞋",
		"凉鞋",
		"长靴",
		"双肩包",
		"皮包",
		"布包",
		"帽子",
		"袜子",
		"手套",
		"腰带",
		"丝巾",
		"围巾",
		"文件"
	];
	// let arrKey = ["weight", "order_no", ""];
	console.log(file[4]);
	console.log(arr);

	if (!_.isEqual(arr, file[4])) {
		ElMessage.error("上传模版错误");
		loading.close();
		return false;
	}
	let goodList = file.splice(5, file.length - 1);
	let arrList: any = [];

	for (let index in goodList) {
		const detail = [];
		let item: any = goodList[index];
		let address: any = await addressCorrect(item[11]);
		for (let i = 0; i < item.length; i++) {
			if (i >= 16 && item[i]) {
				detail.push({
					cate2: arr[i],
					num: item[i]
				});
			}
		}
		let obj: any = {
			order_no: item[0],
			client_code: item[1],
			user_mark: item[2],
			express_type: item[15],
			weight_report: item[8],
			sender: {
				name: item[3],
				area_code: item[4],
				mobile: item[5],
				nation: item[6],
				detailed: item[7]
			},
			client_address: {
				name: item[10],
				area_code: 86,
				mobile: item[12],
				postcode: item[13],
				nation: "中国",
				province: address.province,
				city: address.city,
				district: address.district,
				detailed: address.detailed
			},
			remarks: item[14],
			detail: detail
		};
		arrList.push(obj);
	}
	// let tableList: any = _.values(_.groupBy(arrList, "listNum"));
	// let newList: any = [];
	// tableList.forEach((element: any) => {
	// 	element.forEach((i: any, n: number) => {
	// 		element[0].detail.push(i.goods);
	// 		element[0].total_num += i.goods.num;
	// 		element[0].total_price += i.goods.amount * i.goods.num;
	// 	});
	// 	newList.push(element[0]);
	// });
	TableList.value = [...arrList];
	loading.close();
	// console.log(TableList.value);
};

const delet = (index: any) => {
	TableList.value.splice(index, 1);
};
const drawer = ref(false);
const rowList = ref();
const cheack = (row: any) => {
	drawer.value = true;
	rowList.value = [...row.detail];
	console.log(rowList.value);
};
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	dialogVisible.value = false;
	channelList.value = [];
	formEl.resetFields();
};
const result: any = ref({
	successData: [],
	errorData: []
});
const batch_no = ref("");
const upLoadList = (param: any) => {
	return new Promise<void>((resolve, reject) => {
		createBatch(param)
			.then((res: any) => {
				if (res.data.successData.length) {
					result.value.successData = result.value.successData.concat(res.data.successData);
				}
				if (res.data.errorData.length) {
					result.value.errorData = result.value.errorData.concat(res.data.errorData);
				}
				batch_no.value = res.data.batch_no;
				resolve(res.data);
			})
			.catch(e => {
				resolve(e);
			});
	});
};
const submitOrder = () => {
	if (!TableList.value.length) {
		ElMessage.error("请上传文件");
		return;
	}
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			batch_no.value = "";
			result.value = {
				successData: [],
				errorData: []
			};
			let allTable: any = _.chunk(TableList.value, 10);
			console.log(allTable.length);

			for (let index = 0; index < allTable.length; index++) {
				const element = allTable[index];
				let param: any = {};
				param.line_id = ruleForm.line_id;
				param.channel_id = ruleForm.channel_id;
				param.list = element;
				param.batch_no = batch_no.value;
				await upLoadList(param);
			}
			dialogVisible.value = true;
		} catch (error) {
			console.log(error);
		}
	});
};
</script>

<style lang="scss" scoped>
.card-title {
	margin-bottom: 20px;
	color: var(--el-color-primary);
	&::before {
		position: relative;
		top: 2px;
		display: inline-block;
		width: 4px;
		height: 16px;
		margin-right: 6px;
		content: "";
		background-color: var(--el-color-primary);

		// color: ;
	}
}
.headers {
	background-color: var(--el-color-primary);
}
.total {
	display: flex;
	margin-top: 20px;
	font-size: 14px;
	span {
		margin-left: 5px;
		color: var(--el-color-primary);
	}
}
.buttons {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
.load {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40px;
	cursor: pointer;
	border: 1px dashed var(--el-border-color-light);
	border-radius: 10px;
}
.buttons {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
</style>
